package player;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

import server.Card;
import util.CardParser;
/**
 * Class to show the cards on a JList component
 *
 */
public class CellCardRenderer extends JLabel implements ListCellRenderer {

	private static final long serialVersionUID = 1L;
	private float percent;


	/**
	 * Constructor 
	 * @param percentSize
	 */
	public  CellCardRenderer() {
		this.percent= 100;
	}

	
	/**
	 * Constructor using percentage
	 * @param percentSize
	 */
	public  CellCardRenderer(float percentSize) {
		this.percent= percentSize;
	}
	
	
	@Override
	public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

		if (value!=null) {
			Card o = (Card) value;
			this.setOpaque(true);
		
			this.setVerticalTextPosition(JLabel.BOTTOM);
			this.setHorizontalTextPosition(JLabel.CENTER);
		
			ImageIcon ii = new ImageIcon("cards/"+imageCardRelativePath(o));

			this.setIcon(this.resize(percent, ii));
			this.setVerticalAlignment(CENTER);
			this.setHorizontalAlignment(CENTER);
			this.setToolTipText(o.getNumber() + " of " + o.getSuit());
				
			if (isSelected) this.setBackground(new Color(200,200,250));
			else this.setBackground(Color.white);

			this.setPreferredSize(new Dimension((int) (this.getIcon().getIconWidth()*1.2) ,(int) (this.getIcon().getIconHeight()*1.2) ));
		}
		return this;
	}
	
	
	/**
	 * Resizes the image of the card.
	 * @param percent
	 * @param i
	 * @return
	 */
	private ImageIcon resize(float percent, ImageIcon i) {
	
		Image image = i.getImage();

		int newWidth = (int) (i.getIconWidth()*percent/100);
		int newHeight = (int) (i.getIconHeight()*percent/100);
		
		BufferedImage thumbImage = new BufferedImage(newWidth,newHeight, BufferedImage.TYPE_INT_RGB);
		
	    Graphics2D graphics2D = thumbImage.createGraphics();
	    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	    graphics2D.drawImage(image, 0, 0, newWidth, newHeight, null);


	    return new ImageIcon(thumbImage);
	}
	
	/**
	 * computes the name of card image file from the card value.
	 * @param c
	 * @return
	 */
	private String imageCardRelativePath(Card c) {
		CardParser parser = new CardParser();
		return parser.inputParseCard(c).trim()+".jpg";
	}

}
